import logging
import os
import time
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler

DATABASE_URL = "mysql+pymysql://root:123456@localhost:3306/kl-server-py"

logger = logging.getLogger(__name__)


class CustomFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        # 获取时间戳
        dt = time.localtime(record.created)
        if datefmt:
            output = time.strftime(datefmt, dt)
        else:
            # 标准格式：YYYY-MM-DD HH:MM:SS + .msecs
            output = time.strftime("%Y-%m-%d %H:%M:%S", dt)
            # 强制用点拼接毫秒（:03.0f 确保 3 位）
            output = f"{output}.{int(record.msecs):03d}"
        return output


def setup_logging():
    """配置日志"""
    """配置日志：输出到控制台 + 文件"""
    log_level = "INFO"
    base_log_file = "logs/app"

    # 生成当天日期文件名
    today = datetime.now().strftime("%Y-%m-%d")
    log_file = f"{base_log_file}-{today}.log"

    os.makedirs(os.path.dirname(log_file), exist_ok=True)

    level = getattr(logging, log_level, logging.INFO)

    root_logger = logging.getLogger()
    root_logger.setLevel(level)

    # 使用自定义 Formatter
    formatter = CustomFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)

    # 文件处理器
    file_handler = TimedRotatingFileHandler(
        log_file, when="midnight", interval=1, backupCount=7, encoding="utf-8"
    )
    file_handler.setLevel(level)
    file_handler.setFormatter(formatter)
    root_logger.addHandler(file_handler)

    root_logger.propagate = False
